package solutions.ferpa.ztest.intf;

import br.com.telescope.adsrt.dom.DomSourceCode;
import br.com.telescope.adsrt.lib.*;
import br.com.telescope.t2.ServiceModel;
import br.com.telescope.t2.config.Config;
import br.com.telescope.t2.exception.ApplicationRuntimeException;
import br.com.telescope.t2.exception.UnexpectedException;
import br.com.telescope.t2.feature.CustomActionFeature;
import br.com.telescope.t2.feature.CustomFeature;
import com.asual.lesscss.LessEngine;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import solutions.ferpa.ztest.ent.*;

/**
 * Manutenção de skin.
 * <p>
 * Interface para a manutenção da skin do sistema, permitindo a alteração 
 * dos componentes visuais do sistema.
 * <P>
 * Telescope origin: RTCONFIG.CFG_SKIN
 * <P>
 * @author TELESCOPE - Build task T2 Web Interface Generator
 * <P>
 * @version 0.1
 */
public class CfgSkin extends ServiceModel {
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    public static final String GLOBAL_NAME = "RTCONFIG.CFG_SKIN";
    
    @Override
    public String globalName() {
        return GLOBAL_NAME;
    }
    
    {
        setTitle("Manutenção de skin");
    }
    
    
    // Record items
    private DomSourceCode aPropriedades;
    private DomSourceCode aCssCustom;
    private DomSourceCode aLogotipo;
    private DomSourceCode aHeaderContent;
    private DomSourceCode aFooterContent;
    
    // Query items
    
    @Override
    public void initAttributes() {
        
        aPropriedades = new DomSourceCode();
        aPropriedades.context(ctx).name("PROPRIEDADES").label("Propriedades CSS").format("language:css").unbound(true);
        
        aCssCustom = new DomSourceCode();
        aCssCustom.context(ctx).name("CSS_CUSTOM").label("CSS Custom").format("language:css").unbound(true);
        
        aLogotipo = new DomSourceCode();
        aLogotipo.context(ctx).name("LOGOTIPO").label("Logotipo").format("language:html").unbound(true);
        
        aHeaderContent = new DomSourceCode();
        aHeaderContent.context(ctx).name("HEADER_CONTENT").label("Cabeçalho").format("language:html").unbound(true);
        
        aFooterContent = new DomSourceCode();
        aFooterContent.context(ctx).name("FOOTER_CONTENT").label("Rodapé").format("language:html").unbound(true);
        
    }
    
    @Override
    public String getDefaultOrderBy() {
        return "";
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="CUSTOM">
    public class FCustom extends CustomFeature {
        
        @Override
        public void initForm() {
            addField(aPropriedades, "opt");
            addField(aCssCustom, "opt");
            addField(aLogotipo, "opt");
            addField(aHeaderContent, "opt");
            addField(aFooterContent, "opt");
        }
        
        @Override
        public void preDisplay() {
            try {
                popularCampos();
            } catch (AdsException ex) {
                throw new ApplicationRuntimeException(ex);
            }
        }
        
        @Override
        public void onAction() {
            addSubmit(getFeature("COMPILAR")).label("Salvar").shortCutKey("F3");
        }
        
        {
            setFeatureName("CUSTOM");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="COMPILAR">
    public class FCompilar extends CustomActionFeature {
        
        @Override
        public void initForm() {
        }
        
        @Override
        public void execute() {
            try {
                compilar();
            } catch (AdsException ex) {
                throw new ApplicationRuntimeException(ex);
            }
        }
        
        {
            setFeatureName("COMPILAR");
            setTitle("Compilar");
            setShortCutKey("F3");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="initFeatures">
    
    @Override
    protected void initFeatures() {
        addFeature(new FCustom());
        addFeature(new FCompilar());
        super.initFeatures();
    }
    
    @Override
    public String getDefaultFeature() {
        return "CUSTOM";
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="Getters and Setters">
    
    public String getPropriedades() {
        return aPropriedades.getValue();
    }
    
    public void setPropriedades(String value) {
        this.aPropriedades.setValue(value);
    }
    
    public String getCssCustom() {
        return aCssCustom.getValue();
    }
    
    public void setCssCustom(String value) {
        this.aCssCustom.setValue(value);
    }
    
    public String getLogotipo() {
        return aLogotipo.getValue();
    }
    
    public void setLogotipo(String value) {
        this.aLogotipo.setValue(value);
    }
    
    public String getHeaderContent() {
        return aHeaderContent.getValue();
    }
    
    public void setHeaderContent(String value) {
        this.aHeaderContent.setValue(value);
    }
    
    public String getFooterContent() {
        return aFooterContent.getValue();
    }
    
    public void setFooterContent(String value) {
        this.aFooterContent.setValue(value);
    }
    // </editor-fold>
    
    /**
     * Compilar.
     */
    public void compilar() throws AdsException {
        // <user-code id="5927337" parentId="5927336" hashcode="-1dce6fbf" length="2473">
        // import com.asual.lesscss.LessEngine;
        // import br.com.telescope.t2.config.Config;
        // import java.io.FileWriter;
        // import java.io.BufferedWriter;
        
        Config config = Config.getInstance();
        ctx.readFields(aPropriedades, aCssCustom, aLogotipo, aHeaderContent, aFooterContent);
        
        String skinPath = config.getParameter("RT.UI.SKIN_PATH", "skins/default/");
        String realPath = config.getServletContext().getRealPath(skinPath);
        String configPath = config.getConfigPath();
        
        File configFile = new File(configPath + skinPath + "/config.less");
        
        LessEngine engine = new LessEngine();
        
        ctx.setPreference("RT.UI.CUSTOM_CSS", aCssCustom.getValue());
        ctx.setPreference("APP.UI.LOGO", aLogotipo.getValue());
        
        ctx.setPreference("APP.UI.HEADER_CONTENT", aHeaderContent.getValue().isEmpty() ? null : aHeaderContent.getValue());
        ctx.setPreference("APP.UI.FOOTER_CONTENT", aFooterContent.getValue().isEmpty() ? null : aFooterContent.getValue());
        
        try {
            configFile.createNewFile();
        
            FileWriter writer = new FileWriter(configFile);
            writer.write(aPropriedades.getValue());
            writer.close();
        
            String[] lines = org.apache.commons.io.FileUtils.readLines(new File(realPath + "/less/style.less")).toArray(new String[] {});
            if (lines.length > 0) {
                StringBuilder newStyle = new StringBuilder(20000);
                for (String line : lines) {
        
                    if (line.indexOf("@import ") >= 0) {
                        String importFileName = line.substring(9, line.length() - 2);
                        File importFile = importFileName.equals("config") ? configFile : new File(realPath + "/less/" + importFileName + ".less");
                        newStyle.append(org.apache.commons.io.FileUtils.readFileToString(importFile));
                    } else {
                        newStyle.append(line).append("\n");
                    }
        
                }
                
                StringBuilder css = new StringBuilder(engine.compile(newStyle.toString()));
        
                FileWriter fstream = new FileWriter(realPath + "/css/style.css");
                BufferedWriter out = new BufferedWriter(fstream);
        
                if (aCssCustom.isNotNull()) {
                    css.append("\n/* CSS CUSTOM - RT.UI.CUSTOM_CSS */ \n")
                            .append(engine.compile(aCssCustom.getValue()));
                }
        
                
                out.write(css.toString());
                out.close();
            }
            
            ctx.addMessage("Skin compilada com sucesso");
            doIndex();
        } catch (Exception ex) {
            throw new UnexpectedException(ex);
        }
        // </user-code>
    }
    
    /**
     * Popular propriedades.
     */
    private void popularCampos() throws AdsException {
        // <user-code id="5927329" parentId="5927327" hashcode="6c48bd54" length="1128">
        // import br.com.telescope.t2.exception.UnexpectedException;
        
        Config config = Config.getInstance();
        
        StringBuilder value = new StringBuilder();
        String skinPath = config.getParameter("RT.UI.SKIN_PATH", "skins/default/");
        String configPath = config.getConfigPath(); 
        
        File configFile = new File(configPath + skinPath + "/config.less");
        
        try {
            
            String[] lines = org.apache.commons.io.FileUtils.readLines(configFile).toArray(new String[] {});
            
            for (String line : lines) {
                value.append(line).append("\n");
            }
        
        } catch (Exception ex) {
            throw new UnexpectedException(ex);
        }
        
        aPropriedades.setFormat("language:css");
        aCssCustom.setFormat("language:css");
        aLogotipo.setFormat("language:html");
        aFooterContent.setFormat("language:html");
        aHeaderContent.setFormat("language:html");
        aPropriedades.setValue(value.toString());
        aCssCustom.setValue(ctx.getPreference("RT.UI.CUSTOM_CSS"));
        aLogotipo.setValue(ctx.getPreference("APP.UI.LOGO"));
        
        aFooterContent.setValue(ctx.getPreference("APP.UI.FOOTER_CONTENT"));
        aHeaderContent.setValue(ctx.getPreference("APP.UI.HEADER_CONTENT"));
        // </user-code>
    }
}
